'use strict';

stareal
    .controller("UploadPublishController", function ($scope, $http,$stateParams, $lazyLoader, $api, $alert, $state,localStorageService,$window,$compile,FileUploader) {
        //弹出框水平垂直居中
        $scope.viewsendID=$stateParams.id;
        // $(window).resize(function () {
        //     var win_height = $(window).height();
        //     var win_width = $(window).width();
        //     if (win_width <= 768){
        //         $(".tailoring-content").css({
        //             "top": (win_height - $(".tailoring-content").outerHeight())/2,
        //             "left": 0
        //         });
        //     }else{
        //         $(".tailoring-content").css({
        //             "top": (win_height - $(".tailoring-content").outerHeight())/2,
        //             "left": (win_width - $(".tailoring-content").outerWidth())/2
        //         });
        //     }
        // });
        $api.get("app/view/classifylist",{},true)
            .then(function (ret) {
                // console.log(ret);
                var data=ret.data;
                for(var i=0;i<data.length;i++){
                    if(data[i].id==$scope.currentClassfyID){
                        //  $scope.selectedName=data[i];
                        // console.log($scope.selectedName);
                    }
                }
                $scope.viewclassifyList=ret.data;

            })

        $('#viewclassifyname').val(localStorageService.get("viewshowname")); //观演名称
        //获取可编辑的内容
        $scope.getDetailContent=function(){
            $api.get("app/view/caoretrievelist",{id:$scope.viewsendID}, true)
                .then(function(ret) {
                    var data=ret.data;
                    if(data.thumb!=undefined&&data.thumb!=''&&data.thumb!=null){  //头图
                        $("#finalImg").prop("src",data.thumb);
                        $scope.toppicImg = data.thumb;
                    }
                    if(data.viewname!=undefined&&data.viewname!=''&&data.viewname!=null){  //观演名称
                        $('#viewclassifyname').val(data.viewname);
                    }
                    // if(data.viewaddress!=undefined&&data.viewaddress!=''&&data.viewaddress!=null){  //观演地址
                    //     $('#viewclassifyaddress').val(data.viewaddress);
                    // }
                    // if(data.length_time!=undefined&&data.length_time!=''&&data.length_time!=null){  //观演时长
                    //     $('#viewclassifytimes').val(data.length_time);
                    // }
                    // if(data.viewmoney!=undefined&&data.viewmoney!=''&&data.viewmoney!=null){  //费用
                    //     $('#viewclassifyfare').val(data.viewmoney);
                    // }
                    //观演列别
                    //演出分类
                    if(data.classifyid!=undefined&&data.classifyid!=''&&data.classifyid!=null){  //费用
                     $scope.currentClassfyID=data.classifyid;
                        $('#selectviewclassify').val(data.classifyid);
                    }
                    // var dateStr = data.viewdata;
                    // //获取现在的时间
                    //
                    // var yearNow = new Date().getFullYear();//获取年份
                    // var monthSel = new Date().getMonth()+1;//获取月份
                    // var maxDay = new Date(yearNow,monthSel,0).getDate();//获取当月天数
                    // if(dateStr){
                    //     $scope.year = dateStr.substring(0, 4);
                    //     $scope.month = dateStr.substring(4, 6);
                    //     $scope.day = dateStr.substring(6,8);
                    //     //初始化
                    //     $scope.birthday = dateStr;
                    //     $scope.time = {
                    //         year:Number($scope.year),
                    //         month:Number($scope.month),
                    //         day:Number($scope.day),
                    //     }
                    // }else{//生日不存在的时候
                    //     $scope.birthday='选择观演日期';
                    //     $scope.time = {
                    //         year:yearNow,
                    //         month:monthSel,
                    //         day:maxDay,
                    //     }
                    // }
                    // $scope.yearNows = [];//年份
                    // $scope.monthNow = [];//月份
                    // $scope.dayNow = [];//天数
                    // for(var i=yearNow;i>1899;i--){
                    //     $scope.yearNows.push({
                    //         id:i,
                    //         name:i
                    //     })
                    // }
                    // for(var i=1;i<13;i++){
                    //     $scope.monthNow.push({
                    //         id:i,
                    //         name:i
                    //     })
                    // }
                    // $scope.$watch('time.month',function(newValue){//这个是得监控月份才能获取天数
                    //     maxDay = newValue?new Date(yearNow,newValue,0).getDate():'';
                    //     for(var i=1;i<maxDay+1;i++){
                    //         $scope.dayNow.push({
                    //             id:i,
                    //             name:i
                    //         })

                    })

        }
        if($scope.viewsendID!=''){
            $scope.getDetailContent();
        }

        //弹出图片裁剪框
        $("#replaceImg").on("click",function () {
            $(".tailoring-container").toggle();
        });
        //图像上传
        $("#chooseImg").change(function(event){

            // console.log(event.target);
            $scope.selectImg(event.target);
        })
        $scope.selectImg=function(file) {
            //console.log(file);
            if (!file.files || !file.files[0]){
                return;
            }
            var reader = new FileReader();
            reader.onload = function (evt) {
                var replaceSrc = evt.target.result;
                //更换cropper的图片
                $('#tailoringImg').cropper('replace', replaceSrc,false);//默认false，适应高度，不失真
            }
            reader.readAsDataURL(file.files[0]);
        }
        //cropper图片裁剪
        $('#tailoringImg').cropper({
            aspectRatio: 1.6/1,//默认比例
            preview: '.previewImg',//预览视图
            guides: false,  //裁剪框的虚线(九宫格)
            autoCropArea:1,  //0-1之间的数值，定义自动剪裁区域的大小，默认0.8
            // movable: false, //是否允许移动图片
            dragCrop: false,  //是否允许移除当前的剪裁框，并通过拖动来新建一个剪裁框区域
            movable: true,  //是否允许移动剪裁框
            resizable: false,  //是否允许改变裁剪框的大小
            zoomable: false,  //是否允许缩放图片大小
            mouseWheelZoom: false,  //是否允许通过鼠标滚轮来缩放图片
            touchDragZoom: true,  //是否允许通过触摸移动来缩放图片
            rotatable: true,  //是否允许旋转图片
            crop: function(e) {
                // 输出结果数据裁剪图像。
            }
        });
        //旋转
        $(".cropper-rotate-btn").on("click",function () {
            $('#tailoringImg').cropper("rotate", 45);
        });
        //复位
        $(".cropper-reset-btn").on("click",function () {
            $('#tailoringImg').cropper("reset");
        });
        //换向
        var flagX = true;
        $(".cropper-scaleX-btn").on("click",function () {
            if(flagX){
                $('#tailoringImg').cropper("scaleX", -1);
                flagX = false;
            }else{
                $('#tailoringImg').cropper("scaleX", 1);
                flagX = true;
            }
            flagX != flagX;
        });
        function convertBase64UrlToBlob(urlData) {
            var bytes = window.atob(urlData.split(',')[1]);
            //处理异常,将ascii码小于0的转换为大于0
            var ab = new ArrayBuffer(bytes.length);
            var ia = new Uint8Array(ab);

            for (var i = 0; i < bytes.length; i++) {
                ia[i] = bytes.charCodeAt(i);
            }
            return new Blob([ab], {type: 'image/png'});
        }
        //裁剪后的处理
        $("#sureCut").on("click",function () {
            if ($("#tailoringImg").attr("src") == null ){
                return false;
            }else{
                var cas = $('#tailoringImg').cropper('getCroppedCanvas');//获取被裁剪后的canvas
                var base64url = cas.toDataURL('image/png'); //转换为base64地址形式
                // 裁剪完成的回调函数。this指向图片对象，会将裁剪出的图像数据DataURL作为参数传入
                var fd = new FormData();
                var token = localStorageService.get('token');
                //var url = 'https://api.mydeershow.com/mobile/app/upload/image?accessToken=' + token;//正式
               // var url = 'http://apis.blackwan.cn/mobile/app/upload/image?accessToken='+token;//测试
               var url = 'https://test.djx.api02.opentickets.cn/mobile/app/upload/image?accessToken=' + token;//测试
                // console.log(convertBase64UrlToBlob(dataURL));
                var blog = convertBase64UrlToBlob(base64url);
                if (blog.size > 5242880) {
                    $scope.$apply(function(){
                        $alert.show("图片大小不大于5M");
                    });
                    return false;
                }
                // console.log($scope.selectwidth);
                fd.append('image', convertBase64UrlToBlob(base64url), "image.png");
                $http.post(url, fd, {
                    transformRequest: angular.identity,
                    headers: {
                        'Content-Type': undefined
                    }
                }).success(function (data) {
                    if(data.url!=undefined&&data.url!=''&&data.url!=null){
                        $scope.toppicImg = data.url;
                        $("#finalImg").prop("src",data.url);//显示为图片的形式
                        //关闭裁剪框
                        $scope.closeTailor();
                    }else{
                        $alert.show("图片上传失败，请重新上传");
                    }

                }).error(function(response){
                    $alert.show(response);
                })
            }
        });
        //关闭裁剪框
        $scope.closeTailor=function(){
            $("#tailoringImg").attr("src",'');
            $(".cropper-container").remove();
            $(".tailoring-container").toggle();
        }
         //设置时间


        // $scope.setBirthday = function () {
        //     var h = window.screen.height;
        //     $(".birthday_mask").height(h);
        //     $(".birthday_mask").css({"display":"block"})
        //     $(".birthday_box").css({"display":"block"})
        // }
        // $scope.confirm = function () {
        //     var year = $scope.time.year.toString();
        //     var month = $scope.time.month<10?'0'+$scope.time.month.toString():$scope.time.month.toString();
        //     var day = $scope.time.day<10?'0'+$scope.time.day.toString():$scope.time.day.toString();
        //     var birthday = year+month+day;
        //     $scope.birthday = year+'-'+month+'-'+day
        //     $(".birthday_mask").css({"display":"none"})
        // }
        // $(".birthday_mask").click(function () {
        //     $(this).css({"display":"none"})
        // })
        //发表观演记
        //发表
        $scope.createView=function(){
            $scope.topic_title=localStorageService.get("TopicViewtitle");
            $scope.position= localStorageService.get("currentPOSITIONID");
            $scope.description=localStorageService.get("TopicViewdescriptions");
            $scope.contents=localStorageService.get("TopicViewcontents");
            $scope.textlength=localStorageService.get("TopicViewtextlength");
                if ($scope.toppicImg == '' || $scope.toppicImg == undefined) {
                    $alert.show("封面图不能为空！");
                    return false;
                }
                if($('#selectviewclassify').val()==""){
                    $alert.show("请选择演出分类！");
                    return false;
                }
                if($('#viewclassifyname').val()==''){
                    $alert.show("请填写演出名称！");
                    return false;
                }
                if($scope.topic_title==''||$scope.topic_title==undefined){
                    $alert.show("观演记名称不能为空！");
                    return false;
                }
                // if($('#viewclassifyaddress').val()==''){
                //     $alert.show("请填写演出地址！");
                //     return false;
                // }
                // if($('#viewclassifyfare').val()==''){
                //     $alert.show("请填写门票费用！");
                //     return false;
                // }
                // if($('#viewclassifytimes').val()==''){
                //     $alert.show("请填写观演时长！");
                //     return false;
                // }
                // if(  $scope.time.year==''|| $scope.time.month==''||  $scope.time.day==''){
                //     $alert.show("请选择观演时间！");
                //     return false;
                // }
                //上传演记
                // $scope.viewTime= $scope.time.year+'-'+$scope.time.month+'-'+$scope.time.day;
                //console.log( $scope.viewTime);
                // var fd = new FormData();
                var token = localStorageService.get('token');
             //  var url = 'https://api.mydeershow.com/mobile/app/view/create?source=pc&accessToken='+token;//正式
            var url = 'https://test.djx.api02.opentickets.cn/mobile/app/view/create?source=pc&accessToken='+token;//测试
               // var url = 'http://192.168.1.3/mobile/app/view/create?source=pc&accessToken=' + token;//测试
                $http({
                    method: 'post',
                    url: url,
                    data: {
                        id:  $scope.viewsendID,
                        name: $scope.topic_title,
                        thumb: $scope.toppicImg,
                        content: $scope.contents,
                        describes: $scope.description,
                        position: $scope.position,
                        status: 1,//发表  -1草稿
                        viewname:$('#viewclassifyname').val(),  //观演名称
                        // viewaddress:$('#viewclassifyaddress').val(),//观演地址
                        // viewdata: $scope.viewTime,//观演时间
                        // viewmoney:$('#viewclassifyfare').val(),//门票费用
                        classifyid:$('#selectviewclassify').val(),//分类
                        wordnumber:$scope.textlength,//字数
                        picturenumber:0,//图片张数
                        // lengthtime:$('#viewclassifytimes').val(),//观演时长
                        videonumber:0,
                        type:1, //htmls编辑器
                    },
                    headers: {'Content-Type': 'application/x-www-form-urlencoded'},
                    transformRequest: function (data) {
                        return $.param(data);
                    }
                }).then(function successCallback(response) {
                    var ret=response.data;
                    // console.log(response.data);
                    if(ret.retCode==0){
                        localStorageService.set("TopicViewtitle",'');
                        localStorageService.set("TopicViewcontents",'');
                        localStorageService.set("viewshowname",'');
                        $state.go('my.editview',{},true);
                    }else{
                        $alert.show("发布失败");
                    }
                    //  $state.go('my.view',{},true);
                }, function errorCallback(response) {
                    $alert.show("发布失败");
                });
            }


    });